<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>魅力榜</title>
    <!-- CSS样式保持不变 -->
</head>
<body onload="initPage()">
<div class="container">
    <h1>🌸 魅力榜 🌸</h1>
    <div id="rankListContainer"></div>
</div>

<script>
    async function initPage() {
        try {
            const response = await fetch('/userLike/orderList');
            const data = await response.json();

            if (data.success && Array.isArray(data.list)) {
                renderRankList(data.list);
            } else {
                document.getElementById('rankListContainer').innerText = '暂无排行榜数据';
            }
        } catch (error) {
            console.error('加载排行榜失败:', error);
            document.getElementById('rankListContainer').innerText = '加载数据失败';
        }
    }

    function renderRankList(data) {
        console.log("Rendering rank list with data:", data); // 调试信息
        const container = document.getElementById('rankListContainer');
        container.innerHTML = ''; // 清空旧内容

        data.forEach(item => {
            const div = document.createElement('div');
            div.className = 'rank-item';

            div.innerHTML = `
                <div class="rank-info">
                    用户名：<span>${item.username}</span>
                    点赞数：<span class="like">${item.like}</span>
                </div>
                <button class="send-flower-btn" onclick="sendFlower(${item.id})">送花</button>
            `;

            container.appendChild(div);
        });
    }

    async function sendFlower(id) {
        try {
            const res = await fetch(`/userLike/add?id=${id}`, { method: 'GET' });
            const result = await res.json();

            console.log("Received updated data from server:", result); // 调试信息

            if (result.success && Array.isArray(result.list)) {
                alert('送花成功！');
                renderRankList(result.list); // 使用新的数据重新渲染列表
                window.location.reload(); // 自动刷新页面
            } else {
                alert('送花失败：' + result.msg);
            }
        } catch (error) {
            console.error('送花请求失败:', error);
            alert('网络错误，送花失败');
        }
    }
</script>
</body>
</html>